package menus_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"github.com/gin-gonic/gin"
)

type banner struct {
	ID   uint   `json:"id"`
	Path string `json:"path"`
}

type menuResponse struct {
	models.MenuModel
	Banners []banner `json:"banners"`
}

func (MenusApi) MenusListView(c *gin.Context) {
	// 先查询菜单
	var menuList []models.MenuModel
	var menuId []uint
	common.DB.Order("sort DESC").Find(&menuList).Select("id").Scan(&menuId)
	// 关联查询表
	var menuBanners []models.MenuBannerModel
	common.DB.Preload("BannerModel").Order("sort DESC").Find(&menuBanners, "menu_id in ?", menuId)
	// 组合数据
	var menus []menuResponse
	for _, model := range menuList {
		// 增加 banner 只声明, 不赋值如果是引用类型就返回null 解决 banners字段返回为 null var banners []banner , 使用下面代码就能解决 null banners := make([]banner, 0)
		banners := make([]banner, 0)
		for _, menuBanner := range menuBanners {
			if model.ID != menuBanner.MenuID {
				continue
			}
			banners = append(banners, banner{
				ID:   menuBanner.BannerID,
				Path: menuBanner.BannerModel.Path,
			})
		}
		menus = append(menus, menuResponse{
			MenuModel: model,
			Banners:   banners,
		})
	}
	http.IsOkWithData(menus, c)
}
